package com.wisedu.mobile.auth.controller.v1.db;

import com.wisedu.mobile.common.AjaxResult;
import com.wisedu.mobile.common.annotation.Decrypt;
import com.wisedu.mobile.common.annotation.Encrypt;
import com.wisedu.mobile.common.annotation.SLog;
import com.wisedu.mobile.common.constant.Constants;
import com.wisedu.mobile.common.domain.LoginUser;
import com.wisedu.mobile.common.domain.SysUser;
import com.wisedu.mobile.common.redis.RedisCache;
import com.wisedu.mobile.common.service.SysLoginService;
import com.wisedu.mobile.common.service.TokenService;
import com.wisedu.mobile.common.utils.Base64Utils;
import com.wisedu.mobile.common.utils.MessageUtils;
import com.wisedu.mobile.common.utils.ServletUtils;
import com.wisedu.mobile.common.utils.VerifyCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.nutz.lang.Lang;
import org.nutz.lang.random.R;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Api(tags = "登录验证",position = 1)
@RestController
@RequestMapping("/auth")
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
    @ApiOperation(value = "生成验证码", notes = "生成验证码",httpMethod = "GET")
    @GetMapping("/captchaImage")
    public AjaxResult getCode() throws IOException
    {
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        System.out.println("verifyCode============="+verifyCode);
        // 唯一标识
        String uuid = R.UU32();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        redisCache.setCacheObject(verifyKey, verifyCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try
        {
            NutMap m = Lang.map("uuid", uuid);
            m.put("img", Base64Utils.encode(stream.toByteArray()));
            return AjaxResult.success(m);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        finally
        {
            stream.close();
        }
    }
    /**
     * 登录方法（带验证码）
     * 
     * @param loginname 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    @ApiOperation(value = "用户登录（带验证码）", notes = "POST用户登录签发JWT")
    @PostMapping("/loginWithcode")
    public AjaxResult loginWithcode(String loginname, String password, String code, String uuid)
    {
        try {
            // 生成令牌
            String token = loginService.loginWithCode(loginname, password, code, uuid);
            return AjaxResult.success(MessageUtils.message("user.login.success"),token);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 登录方法（不带验证码）
     *
     * @param loginname 用户名
     * @param password 密码
     * @return 结果
     */
    @ApiOperation(value = "用户登录（不带验证码）", notes = "POST用户登录签发JWT")
    @PostMapping("/login")
    public AjaxResult login(String loginname, String password)
    {
        try {
        // 生成令牌
        String token = loginService.login(loginname, password);
        return AjaxResult.success(MessageUtils.message("user.login.success"),token);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 登录方法（ids）
     *
     * @return 结果
     */
    @ApiOperation(value = "用户登录（ids）", notes = "ids登录界面")
    @GetMapping("/login/ids")
    public String loginIds(HttpServletRequest request)
    {
        String uid = request.getHeader("uid");
        String uname = request.getHeader("uname");
        return null;
    }
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @PostMapping("user")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        AjaxResult ajax = AjaxResult.success(user);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @PreAuthorize("#id<10")
    @GetMapping("user/add")
    public AjaxResult add(int id)
    {
        System.out.println(MessageUtils.message("no.delete.permission")+"find user by id........." + id);
        System.out.println(MessageUtils.message("no.create.permission2")+"=====222====");

        return null;
    }
    @GetMapping("user/del")
    @SLog(tag="logtag",msg = "logmsg",result = true,param = true)
    public AjaxResult del()
    {

        System.out.println(MessageUtils.message("no.delete.permission")+"=====33====");

        return null;
    }

    @GetMapping("user/add2")
    public AjaxResult add2(int id)
    {
        System.out.println("===============2k=============" + id);

        return null;
    }

}
